package com.cuijq.counterv5.controller;

import com.cuijq.counterv5.entity.RequestInfo;
import com.cuijq.counterv5.service.MetricsStorage;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import io.micrometer.core.instrument.util.StringUtils;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Classname MetricsCollector
 * @Description TODO
 * @Date 2021/4/30 14:00
 * @Created by CuiJQ
 */
public class MetricsCollector {

  private static final int DEFAULT_STORAGE_THREAD_POOL_SIZE = 20;
  private MetricsStorage metricsStorage;
  private EventBus eventBus;

  public MetricsCollector(MetricsStorage metricsStorage) {
    this(metricsStorage, DEFAULT_STORAGE_THREAD_POOL_SIZE);
  }

  public MetricsCollector(MetricsStorage metricsStorage, int threadNumToSaveData) {
    this.metricsStorage = metricsStorage;
    this.eventBus = new AsyncEventBus(Executors.newFixedThreadPool(threadNumToSaveData));
    this.eventBus.register(new EventListener());
  }

  public MetricsCollector() {

  }

  public void recordRequest(RequestInfo requestInfo) {
    if (requestInfo == null || StringUtils.isBlank(requestInfo.getApiName())) {
      return;
    }
    eventBus.post(requestInfo);
  }

  public class EventListener {

    @Subscribe
    public void saveRequestInfo(RequestInfo requestInfo) {
      metricsStorage.saveRequestInfo(requestInfo);
    }
  }
}
